﻿using System.Collections.Generic;
using ApplicationLibrary;
using ApplicationLibrary.DBManager;
using ApplicationLibrary.ExtendedControls;
using ApplicationLibrary.SqlConnector;
using Clothes.Items.ModuleData;
using Clothes.Masters.ModuleData;
using Clothes.Items.Preferences;
using ApplicationLibrary.Preferences;
using System;
using System.Windows.Forms;

namespace Clothes.Items.Forms
{
    public partial class Items : ApplicationLibrary.DBManager.DocumentForm
    {
        private EnumsManager<DocType> eDocTypeManager = new EnumsManager<DocType>(Properties.Resources.ResourceManager);
        private EnumsManager<ItemStatus> eItemStatusManager = new EnumsManager<ItemStatus>(Properties.Resources.ResourceManager);
        private ItemsPref itemsPref = null;

        public int LastCustomer { get; set; }

        public Items()
            : base("Items")
        {
            InitializeComponent();
            ReadPreferences();
            keyControl = fncID;
        }

        private void ReadPreferences()
        {
            itemsPref = new PreferencesManager<ItemsPref>(formName, null).ReadPreference();
        }

        #region Virtual Method

        protected override IRadarParameters GetKeyFromDocument()
        {
            return new RadarItemsParam(fncID.CounterNumericValue);
        }

        protected override void OnAttachData()
        {
            dbManager = new dbmanagerItems("ItemsForm", new RadarItems(), this);
            dbManager.AddMaster(this, CL_Items.Name, true);

            fncID.AttachCounterType(GlobalInfo.GetCounter(Properties.Resources.CN_Items), GlobalInfo.CurrentDate, dbManager.Transaction);

            fncInvoice.AttachCounterType(GlobalInfo.GetCounter(Properties.Resources.CN_Invoice), GlobalInfo.CurrentDate, dbManager.Transaction);
            fncRetToCust.AttachCounterType(GlobalInfo.GetCounter(Properties.Resources.CN_ReturnToCustomer), GlobalInfo.CurrentDate, dbManager.Transaction);
            fncBillOfLading.AttachCounterType(GlobalInfo.GetCounter(Properties.Resources.CN_BillOfLading), GlobalInfo.CurrentDate, dbManager.Transaction);

            cbbDesigner.AttachDataReader<Int32>(new RRDesctiptionType(DescriptionType.E_Designer), CL_Descriptions.ID, CL_Descriptions.Description, true, false);
            cbbSize.AttachDataReader<Int32>(new RRDesctiptionType(DescriptionType.E_Size), CL_Descriptions.ID, CL_Descriptions.Description, true);
            cbbColor.AttachDataReader<Int32>(new RRDesctiptionType(DescriptionType.E_Color), CL_Descriptions.ID, CL_Descriptions.Description, true);
            cbbPattern.AttachDataReader<Int32>(new RRDesctiptionType(DescriptionType.E_Pattern), CL_Descriptions.ID, CL_Descriptions.Description, true);
            cbbMaterial.AttachDataReader<Int32>(new RRDesctiptionType(DescriptionType.E_Material), CL_Descriptions.ID, CL_Descriptions.Description, true);
            
            rdrCustomer.RadarForm = new Clothes.Masters.ModuleData.RadarMasters();
            rdrCustomer.AttachCounterType(Counters.Masters.Int(), GlobalInfo.CurrentDate, null);
            rdrCustomer.DescriptionControl = lblDesc;

            eItemStatusManager.AttachTo(cbbStatus);
            eItemStatusManager.DisplayItem += new EnumsManager<ItemStatus>.DisplayEventHandler(eItemStatusManager_DisplayItem);
        }

        bool eItemStatusManager_DisplayItem(ItemStatus e)
        {
            return e != ItemStatus.E_All;
        }

        protected override void OnBindData()
        {
            BindControl(fncID, CL_Items.ID, NullValue.NotSet, Findable.YES);
            BindControl(txtDescription, CL_Items.Description, Findable.YES);
            BindControl(cbbDesigner, CL_Items.Designer, "SelectedValue", Findable.YES);
            BindControl(cbbSize, CL_Items.Size, "SelectedValue", Findable.YES);
            BindControl(cbbColor, CL_Items.Color, "SelectedValue", Findable.YES);
            BindControl(cbbPattern, CL_Items.Pattern, "SelectedValue", Findable.YES);
            BindControl(cbbMaterial, CL_Items.Material, "SelectedValue", Findable.YES);
            BindControl(bdcCateg, CL_Items.Category, "Text", Findable.YES);
            BindControl(rdrCustomer, CL_Items.Customer, "Text", Findable.YES);
            BindControl(ctbReceive, CL_Items.ReceivingData);
            BindControl(ntbPrice, CL_Items.Price);
            BindControl(ckbLowerPrice, CL_Items.CanLowPrice, "DBChecked");
            BindControl(cbbLower, CL_Items.LowPricePerc);
            BindControl(ckbExtended, CL_Items.Extended, "DBChecked");
            BindControl(ntbDayExtended, CL_Items.ExtendedDays);
            BindControl(ctbDeadline, CL_Items.DeadLineDate);
            BindControl(cbbStatus, CL_Items.Status, "SelectedValue", NullValue.NotSet, Findable.YES);
            BindControl(ntbPriceQuote, CL_Items.QuotePrice);
            BindControl(ctbSaleDate, CL_Items.SoldDate);
            BindControl(ntbSalePrice, CL_Items.PriceSale);
            BindControl(ckbInInvoice, CL_Items.Invoice, "DBChecked");
            BindControl(ckbBillOfLading, CL_Items.BillOfLading, "DBChecked");
            BindControl(ckbRetToCust, CL_Items.ReturnToCustomer, "DBChecked");
            BindControl(fncInvoice, CL_Items.InvoiceNo);
            BindControl(fncBillOfLading, CL_Items.BillOfLadingNo);
            BindControl(fncRetToCust, CL_Items.ReturnToCustomerNo);
            BindControl(ckbPrinted, CL_Items.Printed, "DBChecked");

            BindControl(ntbNewPrice);
            BindControl(btnRefresh);
            BindCounter(fncID);
        }

        protected override void OnPrepareAuxData()
        {
            txtDescription.OriginalValue = itemsPref.DescriptionFormat;
            CalculatePriceQuote();
            rdrCustomer.UpdateDescription();
        }

        protected override void OnDisableControlsForEdit()
        {
            ntbNewPrice.Enabled = false;
            DisableControl();
            base.OnDisableControlsForEdit();
        }

        protected override void OnDisableControlsForNew()
        {
            ntbNewPrice.ReadOnly = false;
            cbbStatus.SelectedValue = ItemStatus.E_Null.Int();
            ctbReceive.Today = GlobalInfo.CurrentDate;
            CalculateDeadLine();
            DisableControl();
            base.OnDisableControlsForNew();
        }

        private void CalculateDeadLine()
        {
            ctbDeadline.Today = ctbReceive.Today.AddDays(itemsPref.DayToDeadline);
            if (ckbExtended.Checked)
                ctbDeadline.Today = ctbDeadline.Today.AddDays(ntbDayExtended.Int);
        }

        private void DisableControl()
        {
            ntbDayExtended.Enabled = ckbExtended.Checked;
            cbbLower.Enabled = ckbLowerPrice.Checked;
            ctbSaleDate.Enabled = eItemStatusManager.GetValue() == ItemStatus.E_Sold && ckbInInvoice.Enabled == false;
            ntbSalePrice.Enabled = eItemStatusManager.GetValue() == ItemStatus.E_Sold && ckbInInvoice.Enabled == false;
            ckbRetToCust.Enabled = false;
            ckbInInvoice.Enabled = false;
            ckbBillOfLading.Enabled = false;
            fncInvoice.Enabled = false;
            fncRetToCust.Enabled = false;
            fncBillOfLading.Enabled = false;
            //cbbStatus.Enabled = !(ckbBillOfLading.Checked || ckbInInvoice.Checked || ckbRetToCust.Checked);
        }

        protected override bool OnBeforeAddNew()
        {
            cbbDesigner.SelectedIndex = 0;
            cbbMaterial.SelectedIndex = 0;
            cbbPattern.SelectedIndex = 0;
            cbbSize.SelectedIndex = 0;
            cbbColor.SelectedIndex = 0;
            return true;
        }
        protected override bool OnAfterAddNew()
        {
            txtDescription.OriginalValue = itemsPref.DescriptionFormat;
            rdrCustomer.Text = LastCustomer.ToString();
            rdrCustomer.UpdateDescription();
            return base.OnAfterAddNew();
        }

        protected override void FocusOnNew()
        {
        }

        protected override bool OnBeforeSave()
        {
            bool bOk = true;
            txtDescription.RemoveTags();
            if (rdrCustomer.CounterNumericValue == 0)
            {
                MyMessageBox(Properties.Resources.Msg_Customer, Properties.Resources.Warning, MessageBoxButtons.OK, MessageBoxIcon.Stop);
                errorProvider.SetError(rdrCustomer, Properties.Resources.Msg_Customer);
                bOk = false;
            }

            if (ntbPrice.Double == 0)
            {
                MyMessageBox(Properties.Resources.Msg_Price, Properties.Resources.Warning, MessageBoxButtons.OK, MessageBoxIcon.Stop);
                errorProvider.SetError(ntbPrice, Properties.Resources.Msg_Price);
                bOk = false;
            }

            if (ctbReceive.Today.IsEmpty())
            {
                MyMessageBox(Properties.Resources.Msg_Receive, Properties.Resources.Warning, MessageBoxButtons.OK, MessageBoxIcon.Stop);
                errorProvider.SetError(ctbReceive, Properties.Resources.Msg_Receive);
                bOk = false;
            }
            return bOk && base.OnBeforeSave();
        }

        protected override bool OnEnableToolbarButtons(ToolStripButton button)
        {
            if (button.Name == "tbnEdit" || button.Name == "tbnDelete")
                return !(ckbInInvoice.Checked || ckbRetToCust.Checked);

            return base.OnEnableToolbarButtons(button);
        }

        protected override void OnAddPreferenceButton(ApplicationLibrary.Preferences.PreferenceForm prefForm)
        {
            prefForm.AddPanel(new ItemsPreferencesPanel(formName));
            base.OnAddPreferenceButton(prefForm);
        }

        #endregion

        private void cbbDesigner_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            txtDescription.Designer = cbbDesigner.Text;
        }

        private void cbbSize_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            txtDescription.Sizes = cbbSize.Text;
        }

        private void cbbColor_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            txtDescription.Color = cbbColor.Text;
        }

        private void cbbPattern_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            txtDescription.Print = cbbPattern.Text;
        }

        private void cbbMaterial_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            txtDescription.Material = cbbMaterial.Text;
        }

        private void bdcCateg_DescriptionChanged(object sender, System.EventArgs e)
        {
            txtDescription.Category = bdcCateg.Description;
        }

        private void ckbLowerPrice_CheckedChanged(object sender, System.EventArgs e)
        {
            if (DocumentMode == DBMode.Browse)
                return;

            cbbLower.Enabled = ckbLowerPrice.Checked;
            CalculatePriceQuote();
        }

        private void ckbExtended_CheckedChanged(object sender, System.EventArgs e)
        {
            if (DocumentMode == DBMode.Browse)
                return;

            ntbDayExtended.Enabled = ckbExtended.Checked;
            CalculateDeadLine();
        }

        private void CalculatePriceQuote()
        {
            double val = 1, discounted = 0;
            ntbPriceQuote.Double = ntbPrice.Double * 2;
            
            if (ckbLowerPrice.Checked && double.TryParse(cbbLower.Text, out val))
            {    discounted = ntbPriceQuote.Double - ntbPriceQuote.Double * val / 100;
                 tttItem.SetToolTip(ntbPriceQuote, discounted.ToString("c"));
            }
            ntbNewPrice.Double = discounted;
        }

        private void cbbLower_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            if (DocumentMode == DBMode.Browse)
                return;

            CalculatePriceQuote();
        }

        private void ntbPrice_Validated(object sender, System.EventArgs e)
        {
            errorProvider.SetError(ntbPrice, "");
            CalculatePriceQuote();
        }

        private void ntbDayExtended_Validated(object sender, System.EventArgs e)
        {
            CalculateDeadLine();
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            txtDescription.Text = itemsPref.DescriptionFormat;
            txtDescription.ChangeDescription();
        }

        private void rdrCustomer_Validated(object sender, EventArgs e)
        {
            if (rdrCustomer.Text != LastCustomer.ToString())
                LastCustomer = int.Parse(rdrCustomer.Text);

            errorProvider.SetError(rdrCustomer, "");
        }

        private void cbbStatus_SelectedIndexChanged(object sender, EventArgs e)
        {
            ctbSaleDate.Enabled = eItemStatusManager.GetValue() == ItemStatus.E_Sold && ckbInInvoice.Enabled == false;
            ntbSalePrice.Enabled = eItemStatusManager.GetValue() == ItemStatus.E_Sold && ckbInInvoice.Enabled == false;
            switch(eItemStatusManager.GetValue())
            {
                case ItemStatus.E_Sold:
                    ctbSaleDate.Today = DateTime.Today;
                    ntbSalePrice.Double = ntbPriceQuote.Double;
                    break;
                case ItemStatus.E_Load:
                    ctbSaleDate.Today = ctbSaleDate.Today.EmptyDate();
                    ntbSalePrice.Double = 0;
                    break;
                case ItemStatus.E_Return:
                    ctbSaleDate.Today = DateTime.Today;
                    ntbSalePrice.Double = ntbPrice.Double;
                    break;
                case ItemStatus.E_Beneficence:
                    ctbSaleDate.Today = DateTime.Today;
                    ntbSalePrice.Double = 0;
                    break;
            }
        }

        private void ctbReceive_Validated(object sender, EventArgs e)
        {
            CalculateDeadLine();
            errorProvider.SetError(ctbReceive, "");
        }
    }

    #region DbManager dbmanagerMasters

    /// <summary>
    /// Classe derivata per gestioni particolari
    /// </summary>
    internal class dbmanagerItems : DBManager
    {
        public dbmanagerItems(string name, RadarForm radar, DocumentForm document)
            : base(name, radar, document)
        { }

        protected override void dAdapter_MasterRowUpdating(object sender, SqlABRowUpdatingEventArgs e)
        {
            base.dAdapter_MasterRowUpdating(sender, e);
        }

        protected override string CreateMasterQuery()
        {
            this.Table = new CL_Items();
            QueryBuilder qB = new QueryBuilder();
            qB.AddSelect();
            qB.AddFrom(this.Table);
            qB.AddCompare(CL_Items.ID, "@p1");

            return qB.Query;
        }

        protected override List<SqlABParameter> CreateMasterParam()
        {
            List<SqlABParameter> PList = new List<SqlABParameter>();

            SqlABParameter sParam1 = new SqlABParameter("@p1", CL_Items.ID) { Value = CL_Items.ID.DefaultValue };
            PList.Add(sParam1);
            return PList;
        }

        protected override void SetParameters(ApplicationLibrary.ExtendedControls.IRadarParameters key, DBCollection collection)
        {
            collection.Parameter[0].Value = key[0];
        }
    }

    #endregion

}
